var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "../../services/service", "../config"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const service_1 = require("../../services/service");
    const config_1 = require("../config");
    var ua = navigator.userAgent.toLowerCase();
    exports.isWeixin = ua.match(/MicroMessenger/i) == 'micromessenger';
    function createWeixinClient(weixin) {
        return new Promise((resolve, reject) => {
            var config = {
                debug: false,
                nonceStr: 'mystore',
                jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'getLocation', 'chooseImage', 'getLocalImgData']
            };
            requirejs(['jweixin'], function (wx) {
                var url = encodeURIComponent(location.href.split('#')[0]);
                weixin.jsSignature(config.nonceStr, url).then(function (obj) {
                    config = Object.assign(config, obj);
                    wx.config(config);
                    wx.ready(function () {
                        resolve(wx);
                    });
                    wx.error((res) => {
                        let error = new Error();
                        error.message = res.errMsg;
                        reject(error);
                    });
                });
            }, function (err) {
                reject(err);
            });
        });
    }
    exports.createWeixinClient = createWeixinClient;
    if (exports.isWeixin) {
        // let iframe = document.createElement("iframe");
        // iframe.style.display = "none";
        // iframe.src = "http://web.alinq.cn/weixin/auth/code";
        // document.body.appendChild(iframe);
        // debugger
        // let callbackURL = encodeURIComponent(`http://web.alinq.cn/weixin/auth/callback`);
        // let scope: "snsapi_base" | "snsapi_userinfo" = "snsapi_base";
        // let appId = "wxf1c24c60e3ac13b7";
        // let targetURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${callbackURL}&response_type=code&scope=${scope}#wechat_redirect`
        // fetch("http://web.alinq.cn/weixin/auth/code").then(r => {
        //     debugger;
        // })
    }
    class WeiXinService extends service_1.Service {
        constructor() {
            super();
        }
        url(path) {
            return `${config_1.config.weixinUrl}${path}`;
        }
        openid(value) {
            if (value === undefined)
                return "oYHEKuMV8Kt0QLBIMjmZfxoWwsjU"; //localStorage.getItem('openid');
            if (value == null) {
                localStorage.removeItem("openid");
            }
            localStorage.setItem("openid", value);
        }
        jsSignature(noncestr, url) {
            var data = { noncestr: noncestr, url: url };
            let u = this.url('WeiXin/GetJsSignature');
            return this.getByJson(u, data);
        }
        // async login(code: string): Promise<LoginResult> {
        //     let url = this.url('Member/Login');
        //     let result = await this.postByJson<LoginResult | { UserId: string }>(url, { code });
        //     let userId = (result as { UserId: string }).UserId;
        //     if (userId) {
        //         let memberService = this.createService(MemberService);
        //         let url = `UserMember/User/RegisterById`;
        //         result = await this.postByJson<LoginResult>(url, { userId });
        //     }
        //     // tokens.userToken.value = (result as LoginResult).token;
        //     return result as LoginResult;
        // }
        getPrepayId(openId, order) {
            let url = "http://web.alinq.cn/weixin/pay/prepayid";
            return this.postByJson(url, { openId, order: order });
        }
        getSign(args) {
            return __awaiter(this, void 0, void 0, function* () {
                let url = "http://web.alinq.cn/weixin/paySign";
                let r = yield this.get(url, args);
                return r;
            });
        }
        /** 获取微信配置 */
        getConfig() {
            return __awaiter(this, void 0, void 0, function* () {
                if (!this.config) {
                    let url = "http://web.alinq.cn/weixin/config";
                    this.config = yield this.get(url);
                }
                return this.config;
                ;
            });
        }
        getPayArgs(openid, order) {
            return __awaiter(this, void 0, void 0, function* () {
                let r = yield this.getPrepayId(openid, order);
                debugger;
                let config = yield this.getConfig();
                var args = {
                    appId: config.appId,
                    nonceStr: this.getNonceStr(),
                    'package': "prepay_id=" + r.prepay_id,
                    timeStamp: this.getTimeStamp(),
                    signType: 'MD5',
                };
                let paySign = yield this.getSign(args);
                args["paySign"] = paySign;
                return args;
            });
        }
        getNonceStr() {
            var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var maxPos = $chars.length;
            var noceStr = "";
            for (let i = 0; i < 32; i++) {
                noceStr += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return noceStr;
        }
        getTimeStamp() {
            var timestamp = new Date().getTime();
            var timestampstring = timestamp.toString(); //一定要转换字符串
            return timestampstring;
        }
        weixinPay(prepayId) {
            /// <returns type="jQuery.Deferred"/>
            function getTimeStamp() {
                var timestamp = new Date().getTime();
                var timestampstring = timestamp.toString(); //一定要转换字符串
                return timestampstring;
            }
            function getNonceStr() {
                var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                var maxPos = $chars.length;
                var noceStr = "";
                for (var i = 0; i < 32; i++) {
                    noceStr += $chars.charAt(Math.floor(Math.random() * maxPos));
                }
                return noceStr;
            }
            return new Promise((resolve, reject) => {
                var nonceStr = getNonceStr();
                var timeStamp = getTimeStamp();
                var pack = "prepay_id=" + prepayId;
                var paySignatureDeferred = this.paySignature(nonceStr, pack, timeStamp);
                paySignatureDeferred.then(function (data) {
                    window['WeixinJSBridge'].invoke('getBrandWCPayRequest', {
                        "appId": data.appId,
                        "nonceStr": nonceStr,
                        "package": pack,
                        "timeStamp": timeStamp,
                        "signType": 'MD5',
                        "paySign": data.paySign //微信签名
                    }, function (res) {
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            resolve();
                        }
                        else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                            reject();
                        }
                        else {
                            alert(res.err_msg);
                            let err = { name: "", message: res.err_msg };
                            reject(err);
                        }
                    });
                });
            });
        }
        paySignature(nonceStr, pack, timeStamp) {
            /// <returns type="jQuery.Deferred"/>
            var data = { nonceStr: nonceStr, 'package': pack, timeStamp: timeStamp };
            return this.postByJson('WeiXin/GetPaySignature', data);
        }
    }
    exports.WeiXinService = WeiXinService;
});
